<template>
  <!-- 主容器 -->
  <div>
    <!-- 弹窗组件 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="65%"
      append-to-body
      @close="dialogVisible=false">

      <div name="开发信息提示" v-if="isInDevMode">
        queryKeyWord：{{ queryKeyWord }}
        <hr>
        dialogTitle：{{ dialogTitle }}
        <hr>
        stringAfterUrl：{{ stringAfterUrl }}
        <hr>
        fineReportUrl：{{ fineReportUrl }}
        <hr>
        currentSelectedFineReportId：{{ currentSelectedFineReportId }}
        <hr>
        fineReportOptions：{{ fineReportOptions[0] }}
        <hr>
      </div>

      <el-row :gutter="10">
        <el-col :span="18">
              <!-- 报表类型选择表单 -->
          <el-form>
            <el-form-item label="报表类型">
              <el-select v-model="currentSelectedFineReportId">
                <el-option
                  v-for="report in fineReportOptions"
                  :value="report.id"
                  :label="report.moduleName"
                  :key="report.id"/>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <!-- 确认对账按钮 -->
          <el-button type="primary" @click="confirmStatement" plain>确认对账</el-button>
        </el-col>
      </el-row>

      

      <!-- 报表展示的 iframe -->
      <iframe :src="fineReportUrl" class="fineReportPrintFrame"></iframe>

    </el-dialog>
  </div>
</template>

<script>
import {getListFineReport} from "@/api/base/fineReport";
import {getIceConf,getDiscRuleByConId} from "@/api/contract/rules";
import {getConIdByStatementId} from "@/api/contract/conbusiness"

export default {
  name: 'printFineReportDialog',
  data() {
    return {
      // 作弊码：从localStorage中获取是否处于开发模式，值为true或false
      isInDevMode: localStorage.getItem('isInDevMode') === 'true',

      // 报表选项
      fineReportOptions: [],
      // 弹窗可见性
      dialogVisible: false,
      // 当前选择的报表ID
      currentSelectedFineReportId: null,
      // 装卸船计费单价
      unitPrice:{
        '20E':0,
        '20F':0,
        '40E':0,
        '40F':0
      }
    };
  },
  methods: {
    // 打开弹窗
    openDialog() {
      // 避免未勾选数据时computed函数报错
      if (this.stringAfterUrl!==''){
        // 获取装卸船计费单价
        this.getUnitPrice()
      }
      this.dialogVisible = true;
    },
    // 获取报表选项（根据props传入的queryKeyWord）
    async fetchFineReportOptions() {
      try {
        // 查询参数
        const queryParam = {
          menuName: this.queryKeyWord,
        };
        // 执行查询
        const response = await getListFineReport(queryParam);
        // 获取查询结果，赋值给报表选项
        this.fineReportOptions = response.data;
        // 从localStorage获取上次选择的ID
        const lastSelectedId = localStorage.getItem(`帆软报表组件-${this.queryKeyWord}-上次选择的id`);
        // 如果上次选择的ID存在，并且在报表选项中也存在对应的项
        if (lastSelectedId && this.fineReportOptions.some(option => option.id === lastSelectedId)) {
          // 则将当前选择的报表ID设置为上次选择的ID
          this.currentSelectedFineReportId = lastSelectedId;
        } else {
          // 否则，默认选择第一个
          this.currentSelectedFineReportId = this.fineReportOptions[0]?.id || null;
        }
      } catch (error) {
        console.error('获取报表选项出错:', error);
      }
    },

    // 确认对账
    confirmStatement() {
      // 执行对账操作
      this.$emit('confirmStatement');
    },
    
    // 获取装卸船计费单价
    async getUnitPrice(){
      if (this.stringAfterUrl!==''){
        // 初始化unitPrice
        this.unitPrice = {
          '20E':0,
          '20F':0,
          '40E':0,
          '40F':0
        }
        // 根据statementId查询该对账单对应的计费合同conId
        const responseConId = await getConIdByStatementId(this.stringAfterUrl)
        // 查找该合同下的装卸船计费规则
        const responseConRuleId = await getDiscRuleByConId(responseConId.data)
        // 如果该合同下有装卸船的计费规则则返回该规则的ruleId，否则返回-1
        if (responseConRuleId.data>0){
          // 根据ruleId获取ICE规则树
          const responseIce = await getIceConf(responseConRuleId.data)
          const iceShowNode = responseIce.root
          // 遍历ICE规则树，查询计费单价
          this.iterateTree(iceShowNode)
        }
        console.log(this.unitPrice)
      }
    },

    // 递归遍历ICE树查询单价
    iterateTree(node){
      // 递归遍历ICE树
      if (node.children!==null&&node.children.length!==0){
        for (let i = 0; i < node.children.length; i++) {
          this.iterateTree(node.children[i])
        }
      }
      // 此处判断条件写死了，故系统上配置合同时需要按照以下格式给标准计费结点进行命名
      if (node.showConf.nodeType===6){
        if (node.showConf.nodeName.includes('标准箱')&&node.showConf.nodeName.includes('20E')){
          this.unitPrice["20E"] = node.showConf.nodeInfo.iceFields[0].value
        }
        if (node.showConf.nodeName.includes('标准箱')&&node.showConf.nodeName.includes('20F')){
          this.unitPrice["20F"] = node.showConf.nodeInfo.iceFields[0].value
        }
        if (node.showConf.nodeName.includes('标准箱')&&node.showConf.nodeName.includes('40E')){
          this.unitPrice["40E"] = node.showConf.nodeInfo.iceFields[0].value
        }
        if (node.showConf.nodeName.includes('标准箱')&&node.showConf.nodeName.includes('40F')){
          this.unitPrice["40F"] = node.showConf.nodeInfo.iceFields[0].value
        }
      }
    },

  },
  props: {
    // 用于搜索的关键字
    queryKeyWord: {
      type: String,
      default: '对账单',
    },
    // 弹窗标题
    dialogTitle: {
      type: String,
      default: '打印帆软报表',
    },
    // URL后的字符串
    stringAfterUrl: {
      type: String,
      default: '',
    },
  },
  watch: {
    // 监听搜索关键字的变化，重新获取报表选项
    async queryKeyWord() {
      await this.fetchFineReportOptions();
    },
    // 监听当前选择的报表ID的变化，保存到localStorage
    currentSelectedFineReportId(newVal) {
      // 保存用户选择的选项到localStorage
      localStorage.setItem(`帆软报表组件-${this.queryKeyWord}-上次选择的id`, newVal);
    },
  },
  computed: {
    // 根据当前选择的报表ID，获取对应的报表URL并拼接URL后的字符串
    fineReportUrl() {
      const selectedOption = this.fineReportOptions.find((item) => item.id === this.currentSelectedFineReportId);
      console.log(selectedOption)
      if(selectedOption!==undefined&&selectedOption!==null&&selectedOption.moduleName==='云浮港装卸船对账单'){
        console.log(this.unitPrice)
        let param20E = '&E20=' + this.unitPrice["20E"].toString()
        let param20F = '&F20=' + this.unitPrice["20F"].toString()
        let param40E = '&E40=' + this.unitPrice["40E"].toString()
        let param40F = '&F40=' + this.unitPrice["40F"].toString()
        return selectedOption?.moduleUrl + this.stringAfterUrl + param20E + param20F + param40E +param40F;
      }else{
        return selectedOption?.moduleUrl + this.stringAfterUrl || '';
      }
      
    },
  },
  created() {
    // 获取报表选项
    this.fetchFineReportOptions();
  }
};
</script>

<style scoped>
/* 报表展示的iframe样式 */
.fineReportPrintFrame {
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  min-height: 800px;
  background: #fff;
}
</style>
